package com.ligongmusic.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
//import android.widget.Toast;

import com.ligongmusic.R;
import com.ligongmusic.activity.CommentsActivity;
import com.ligongmusic.activity.MusicActivity;
import com.ligongmusic.adapter.UniversalAdapter;
import com.ligongmusic.adapter.ViewHolder;
import com.ligongmusic.base.BaseFragment;
import com.ligongmusic.domain.DynamicDomain;
import com.ligongmusic.domain.MusicInfo;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.LoggerUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.NetWorkUtils.NetWorkCallBack;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.view.MyToast;
import com.ligongmusic.view.XListView;
import com.ligongmusic.view.XListView.IXListViewListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

public class Dynamic extends BaseFragment implements IXListViewListener {

    public static DisplayImageOptions options1 = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.head) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.drawable.head)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.head)  //设置图片加载/解码过程中错误时候显示的图片
            .cacheInMemory(true)//设置下载的图片是否缓存在内存中
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型
            .build();//构建完成;
    public static DisplayImageOptions options2 = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.music_icon) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.drawable.music_icon)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.music_icon)  //设置图片加载/解码过程中错误时候显示的图片
            .cacheInMemory(true)//设置下载的图片是否缓存在内存中
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型
            .build();//构建完成;
    private XListView mListView;
    private List<DynamicDomain> musics;
    private MyToast toast;
    private int page = 0;
    private boolean hasData = true;
    //	private int playingMusic = -1;
    private UniversalAdapter<DynamicDomain> adapter;
    private Handler mHandler = new Handler();
    private boolean isNext = true;

    @Override
    protected View layoutInflater(LayoutInflater inflater, ViewGroup container,
                                  Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dynamic, null);
    }

    @Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
            //相当于Fragment的onResume
            if (isNext || GlobalParams.isRefreshDynamic) {
                GlobalParams.isRefreshDynamic = false;
                getData();
            }
        } else {
            //相当于Fragment的onPause
        }
	}

    @SuppressWarnings("deprecation")
    @Override
    protected void getData() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("token", GlobalParams.token));
        pairs.add(new BasicNameValuePair("page", page + ""));
        pairs.add(new BasicNameValuePair("size", "10"));
        pairs.add(new BasicNameValuePair("loginname", GlobalParams.userName));
        NetWorkUtils.getRequest(pairs, GlobalParams.GET_DYNAMIC, new NetWorkCallBack() {
            @Override
            public void success(String result) {
                isNext = false;
                Log.e("LoggerUtils", "Dynamic:" + result);
                onLoad();
                if (musics == null)
                    musics = new ArrayList<DynamicDomain>();
                if (page == 0)
                    musics.clear();
                List<DynamicDomain> temp = JsonUtils.jsonToBeanList(result, DynamicDomain.class);
                mListView.setPullLoadEnable(temp.size() == 10);
                if (temp == null)
                    return;
                hasData = temp.size() == 10;
                for (int i = 0; i < temp.size(); i++)
                    musics.add(temp.get(i));
                setAdapter();
            }

            @Override
            public void error(String message) {
                isNext = true;
                onLoad("刷新失败");
                LoggerUtils.getLog(Dynamic.class).error(message);
            }

            @Override
            public void error() {
                // TODO Auto-generated method stub
                isNext = true;
            }
        });
    }

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(StringUtils.getTime(System.currentTimeMillis()));
    }

    private void onLoad(String message) {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(message);
    }


    private void setAdapter() {
        if (GlobalParams.isChanged) {
            adapter = null;
            GlobalParams.isChanged = false;
        }
        if (adapter == null) {
            adapter = new UniversalAdapter<DynamicDomain>(getActivity(), musics, R.layout.music_dynamic_item) {
                @Override
                public void convert(ViewHolder holder, final DynamicDomain t, final int position) {
//					LoggerUtils.getLog(Dynamic.class).error(t == null ? "null" : t.toString());
                    // 头像
                    ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + t.getPhoto(), (ImageView) holder.getView(R.id.user_head), options1);
                    holder.setText(R.id.tv_upload_date, /*t.getUpload_date() == null ? "" : */StringUtils.getYear(t.getUpload_date()));
                    // 设置字体大小、颜色
                    String nick_name = t.getNick_name();
                    if (StringUtils.isEmpty(nick_name))
                        nick_name = t.getPhone();
//					LoggerUtils.getLog(Dynamic.class).error(nick_name == null ? "null" : nick_name);
                    SpannableStringBuilder builder = new SpannableStringBuilder(nick_name + "上传了单曲");
                    AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(30);
                    ForegroundColorSpan span = new ForegroundColorSpan(getResources().getColor(R.color.color_red));
                    builder.setSpan(span, 0, nick_name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    builder.setSpan(sizeSpan, 0, nick_name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    TextView shareInfo = holder.getView(R.id.tv_share_info);
                    shareInfo.setText(builder);
                    ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + t.getCover(), (ImageView) holder.getView(R.id.music_icon), options2);
                    holder.getView(R.id.rl_music).setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getActivity(), MusicActivity.class);
                            if (GlobalParams.playing_song_id == -1) {//首次播放
                                //记录播放id
                                GlobalParams.playing_song_id = t.getSong_id();
                                intent.putExtra("player", MusicActivity.MUSIC_NEW);// 新音乐
                            } else {//非首次播放
                                if (GlobalParams.playing_song_id == t.getSong_id())
                                    intent.putExtra("player", MusicActivity.MUSIC_CONTINUE);
                                else {
                                    intent.putExtra("player", MusicActivity.MUSIC_NEW);// 新音乐
                                    GlobalParams.playing_song_id = t.getSong_id();// 记录当前播放
                                }
                            }
                            intent.putExtra("info", t);
//							ArrayList<MusicInfo> infos = new ArrayList<MusicInfo>();
//							infos.add(new MusicInfo(t.getSong_name(), GlobalParams.MUSIC_URL + t.getLyric(), GlobalParams.MUSIC_URL + t.getSong_src(), t.getLike_count(), t.getComment_count(), t.getSong_id(), t.getStatus()));
//							intent.putParcelableArrayListExtra("music", infos);
//							intent.putExtra("from", MusicActivity.DYNAMIC);
                            getActivity().startActivityForResult(intent, 0x6);
                        }
                    });
                    holder.setText(R.id.tv_music_name, t.getSong_name());
                    holder.setText(R.id.tv_singer, t.getMusician_name() + "");
                    TextView priseNum = holder.getView(R.id.tv_prise_num);
                    TextView commentsNum = holder.getView(R.id.tv_comments_num);
                    priseNum.setText("赞（" + t.getLike_count() + "）");
                    Drawable drawable = null;
                    if (!GlobalParams.isLogin || t.getStatus() == 0)// 未赞
                        drawable = getResources().getDrawable(R.drawable.prise_off);
                    else
                        drawable = getResources().getDrawable(R.drawable.small_praise);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    priseNum.setCompoundDrawables(drawable, null, null, null);
                    commentsNum.setText("评论（" + t.getComment_count() + "）");
                    priseNum.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!GlobalParams.isLogin) {
//								Toast.makeText(getActivity(), "请先登录再操作", Toast.LENGTH_SHORT).show();
                                toast.toastShow("请先登录再操作");
                                return;
                            }
                            praise(t.getSong_id(), t.getMusician_id(), t.getStatus(), position);
                        }
                    });
                    commentsNum.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!GlobalParams.isLogin) {
                                toast.toastShow("请先登录再操作");
//								Toast.makeText(getActivity(), "请先登录再操作", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            Intent intent = new Intent(getActivity(), CommentsActivity.class);
                            intent.putExtra("comments", t);
                            startActivityForResult(intent, 0x6);
                        }
                    });
                }
            };
            mListView.setAdapter(adapter);
        } else
            adapter.refresh(musics);
    }

    @Override
    protected void initView() {
        toast = new MyToast(getActivity());
        mListView = getView(R.id.dynamic_list);
        mListView.setPullLoadEnable(true);
        mListView.setPullRefreshEnable(true);
        mListView.setXListViewListener(this);
        hasData = true;
        musics = null;
        page = 0;
        getData();
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                hasData = true;
                page = 0;
                getData();
            }
        }, 1000);
    }

    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (hasData) {
                    page++;
                    getData();
                } else {
                    onLoad();
                }
            }
        }, 1000);
    }

    /**
     * 点赞
     */
    @SuppressWarnings("deprecation")
    private void praise(int sid, int personid, final int exastatus, final int position) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("songid", sid + ""));
        pairs.add(new BasicNameValuePair("loginname", GlobalParams.userName));
        pairs.add(new BasicNameValuePair("token", GlobalParams.token));
        NetWorkUtils.getRequest(pairs, GlobalParams.PRISE, new NetWorkCallBack() {
            @Override
            public void success(String result) {
                GlobalParams.isRefreshRanking = true;
                LoggerUtils.getLog(Dynamic.class).error(result);
                if (exastatus == 0) {
                    musics.get(position).setStatus(1);
                    musics.get(position).setLike_count(musics.get(position).getLike_count() + 1);
                } else {
                    musics.get(position).setStatus(0);
                    musics.get(position).setLike_count(musics.get(position).getLike_count() - 1);
                }
                adapter.refresh(musics);
            }

            @Override
            public void error(String message) {
                LoggerUtils.getLog(Dynamic.class).error(message);
            }

            @Override
            public void error() {
                // TODO Auto-generated method stub
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 0x5 || resultCode == 0x6) {
//			if (musics != null)
//				musics.clear();
            if (mListView == null) {
                initView();//如果界面被销毁了，则重新创建界面
            } else {
                getData();// 刷新数据
            }
            LoggerUtils.getLog(Dynamic.class).error("onResult");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
